package week12.producer;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class JMSProducer {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    public static void main(String[] args) {
        // 连接工厂，用来生产Connection
        ConnectionFactory connectionFactory;
        // 连接
        Connection connection = null;
        // 会话，接收或者发送消息的线程
        Session session;
        // 消息的目的地
        Destination queueDestination;
        Destination topicDestination ;
        // 消息发送者
        MessageProducer queueProducer;
        MessageProducer topicProducer;
        try {
            // 实例化连接工厂
            connectionFactory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKEURL);
            // 通过连接工厂获取连接
            connection = connectionFactory.createConnection();
            // 启动连接
            connection.start();
            // 获取Session
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建消息队列，queue
            queueDestination = session.createQueue("week12.topic09");
            // 创建消息生产者
            queueProducer = session.createProducer(queueDestination);
            // 发送消息
            sendMessage(session, queueProducer);



            session.commit();


        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }           
        }
    }

    /**
     * @Description 发送消息
     * @param session
     * @param messageProducer
     * @throws JMSException 
     */
    public static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
        for(int i = 0; i < 3; i++) {
            TextMessage message = session.createTextMessage("ActiveMQ 发送的消息" + i);
            System.out.println("ActiveMQ 发送的消息" + i);
            messageProducer.send(message);
        }
    }

}
